package other.xsy.pms;

import com.alibaba.fastjson.JSONObject;
import com.rkhd.platform.sdk.ScheduleJob;
import com.rkhd.platform.sdk.exception.ScriptBusinessException;
import com.rkhd.platform.sdk.log.Logger;
import com.rkhd.platform.sdk.log.LoggerFactory;
import com.rkhd.platform.sdk.model.QueryResult;
import com.rkhd.platform.sdk.model.XObject;
import com.rkhd.platform.sdk.param.ScheduleJobParam;
import com.rkhd.platform.sdk.service.FutureTaskService;
import com.rkhd.platform.sdk.service.XoqlService;
import com.rkhd.platform.sdk.task.FutureTask;
import other.xsy.pms.utils.HCXObjectService;

import java.util.List;

/**
 * @Description: 定时执行同步失败的销售机会
 * @Author: 黎炎松
 * @Date: 2024/4/10 10:55
 */
public class OpportunityToPmsSchedule implements ScheduleJob, FutureTask {

    private static HCXObjectService hcxObjectService = new HCXObjectService();
    private static XoqlService xoqlService = XoqlService.instance();
    private static final Logger logger = LoggerFactory.getLogger();
    private static String LOGGER_MSG = "定时任务再次执行同步失败的销售机会 ==> ";

    @Override
    public void execute(ScheduleJobParam scheduleJobParam) {
        logger.debug(LOGGER_MSG + " 开始");
        try {
            String messageId = FutureTaskService.instance().addFutureTask(OpportunityToPmsSchedule.class, "");
            logger.info(LOGGER_MSG + "异步ID:" + messageId);
        } catch (Exception e) {
            logger.error(LOGGER_MSG + " ----- 发生异常：" + e.getMessage());
        }
    }

    @Override
    public void execute(String s) throws ScriptBusinessException {
        dealSyncErrorOpportunity();
    }


    public static void main(String[] args) throws Exception {
        new OpportunityToPmsSchedule().dealSyncErrorOpportunity();
    }


    /**
     * 处理同步失败的销售机会
     */
    public void dealSyncErrorOpportunity() {
        try {
            // 查询同步失败的销售机会  推送前置判断 1.业务类型为 渠道项目   2.销售阶段 等于 商机识别 不进行同步  3.审批通过
            String sql = "select id,SyncStatus__c,errorInfo__c,syncCount__c from opportunity " +
                    " where SyncStatus__c != 2 and (errorInfo__c != '销售OA账号为空;' or errorInfo__c is null) and (syncCount__c < 6 or syncCount__c is null)";
            List<JSONObject> records = xoqlService.query(sql, true).getRecords();
            if (records.size() <= 0) {
                logger.debug(LOGGER_MSG + " 无需要同步的销售机会");
                return;
            }

            SyncOpportunityToPmsTrigger syncOpportunityToPmsTrigger = new SyncOpportunityToPmsTrigger();
            // 重新执行
            for (JSONObject record : records) {
                syncOpportunityToPmsTrigger.executeSync(record.getLong("id"));
            }
        } catch (Exception e) {
            logger.debug(LOGGER_MSG + " 同步异常: " + e.getMessage());
        }
    }

}
